#!/usr/bin/env bash

export DEBIAN_FRONTEND=noninteractive
ufw disable

SITE_PATH='/var/www/opencart'

echo "deb https://mirrors.tuna.tsinghua.edu.cn/ubuntu/ zesty main restricted
deb https://mirrors.tuna.tsinghua.edu.cn/ubuntu/ zesty-updates main restricted
deb https://mirrors.tuna.tsinghua.edu.cn/ubuntu/ zesty universe
deb https://mirrors.tuna.tsinghua.edu.cn/ubuntu/ zesty-updates universe
deb https://mirrors.tuna.tsinghua.edu.cn/ubuntu/ zesty multiverse
deb https://mirrors.tuna.tsinghua.edu.cn/ubuntu/ zesty-updates multiverse
deb https://mirrors.tuna.tsinghua.edu.cn/ubuntu/ zesty-backports main restricted universe multiverse
deb https://mirrors.tuna.tsinghua.edu.cn/ubuntu/ zesty-security main restricted
deb https://mirrors.tuna.tsinghua.edu.cn/ubuntu/ zesty-security universe
deb https://mirrors.tuna.tsinghua.edu.cn/ubuntu/ zesty-security multiverse
" > /etc/apt/sources.list

apt-get -q -y update

apt-get -q -y install ssh openssl
apt-get -q -y install libcurl4-openssl-dev
apt-get -q -y autoremove

# Install MySQL
DEBIAN_FRONTEND=noninteractive apt-get -q -y install mysql-server mysql-client

# Create Database instance
mysql -u root -e "use mysql;update user set host = '%';"
mysql -u root -e "GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' IDENTIFIED BY '' WITH GRANT OPTION;"
mysql -u root -e "flush privileges;"
mysql -u root -e "create database opencart;"

# Install PHP
apt-get -q -y install php-common php php-mysql php-gd php-mysql php-bz2 php-dev php-xml php-mcrypt php-intl php-mbstring php-zip php-pear php-soap php-bcmath php-dom php-curl libapache2-mod-php

# apache2
apt-get -y install apache2
a2enmod rewrite
echo "
<VirtualHost *:80>
        ServerAdmin webmaster@localhost
        DocumentRoot $SITE_PATH
		ServerName 192.168.33.10
		
		<Directory '$SITE_PATH'>
			Options Indexes FollowSymLinks MultiViews
			AllowOverride All
			Order allow,deny
			allow from all
		</Directory>
</VirtualHost>
" > /etc/apache2/sites-available/opencart.conf
echo "ServerName localhost" >> /etc/apache2/opencart.conf
a2ensite opencart.conf

# memcached
apt-get install php-memcached memcached libevent-dev
sed -i 's/session.save_handler = files/session.save_handler = memcached\nsession.save_path = "127.0.0.1:11211"\n/g' /etc/php/7.0/apache2/php.ini

# auto start
echo "#!/bin/sh -e
service apache2 start
exit 0" > /etc/rc.local

# Post Up Message
echo "请把opencart安装包放到setup下，再执行以下代码："
echo "vagrant ssh"
echo "sudo /vagrant/scripts/setup.sh"
echo "然后访问 http://192.168.33.10/"